package com.leonzhangxf.vdt.validation;

import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.*;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import java.util.List;

/**
 * A demonstrate for field validation.
 *
 * @author leonzhangxf
 * @date 20190423
 */
@Configuration
@ComponentScan({"com.leonzhangxf.vdt.validation"})
public class ApplicationForValidationStarter {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext =
            new AnnotationConfigApplicationContext(ApplicationForValidationStarter.class);

        Validator validator = applicationContext.getBean(Validator.class);
        Student student = Student.builder().name("张晓峰").age(200).email("leonzhangxf@gmail.com").build();

        DataBinder dataBinder = new DataBinder(student);
        dataBinder.addValidators(validator);
        dataBinder.validate();

        BindingResult bindingResult = dataBinder.getBindingResult();
        if (bindingResult.hasErrors()) {
            System.out.println("Validate has error.");
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println(fieldError.getDefaultMessage());
            }
        } else {
            System.out.println("Validate success.");
        }

        System.out.println("==========================================");
        BeanPropertyBindingResult bindingResult1 = new BeanPropertyBindingResult(student, "student");
        ValidationUtils.invokeValidator(validator, student, bindingResult1);
        if (bindingResult1.hasErrors()) {
            System.out.println("Validate has error.");
            List<FieldError> fieldErrors = bindingResult1.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println(fieldError.getDefaultMessage());
            }
        }
    }

    @Bean
    public LocalValidatorFactoryBean validator() {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setMessageInterpolator(new ParameterMessageInterpolator());
        return localValidatorFactoryBean;
    }
}
